package com.inspur.sc.springboot.service.impl;

import com.inspur.sc.springboot.convert.SysGroupConvertSysGroupVO;
import com.inspur.sc.springboot.dao.SysGroupDao;
import com.inspur.sc.springboot.dao.SysGroupRoleDao;
import com.inspur.sc.springboot.entity.SysGroup;
import com.inspur.sc.springboot.entity.SysGroupRole;
import com.inspur.sc.springboot.service.SysGroupService;
import com.inspur.sc.springboot.vo.SysGroupVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class SysGroupServiceImpl implements SysGroupService {

    @Autowired
    private SysGroupDao groupDao;

    @Autowired
    private SysGroupRoleDao groupRoleDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(SysGroup group,List<Integer> roles) {
        try {
            groupDao.save(group);
            int i=groupRoleDao.deleteSysGroupRolesBySysGroupId(group.getId());
            if(i>0){
                roles.forEach(roleId->{
                    SysGroupRole groupRole=new SysGroupRole();
                    groupRole.setSysGroupId(group.getId());
                    groupRole.setSysRoleId(roleId);
                    groupRoleDao.save(groupRole);
                });
            }
            return true;
        }catch (Exception e){
            log.error(e.getMessage());
            return false;
        }
    }

    @Override
    public SysGroupVO findById(Integer groupId) {
        SysGroup group=groupDao.findById(groupId).get();
        return SysGroupConvertSysGroupVO.convert(group);
    }

    @Override
    public List<SysGroup> findAll() {
        return groupDao.findAll();
    }

    @Override
    public Page<SysGroup> findAll(Pageable pageable) {
        return groupDao.findAll(pageable);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteById(Integer groupId) {
        try{
            groupDao.deleteById(groupId);
            return true;
        }catch (Exception e){
            log.error(e.getMessage());
            return false;
        }
    }
}
